<?php
namespace backend\modules\admin\models;

use yii;
use yii\db\ActiveRecord;
use yii\helpers\Url;
use backend\modules\admin\models\RolePriv;
use backend\modules\admin\models\Menu;
use backend\components\Utools;
class Role extends ActiveRecord
{
    public $menuArray=[];
    /**
     * Role类关联数据库表名称 admin_role
     */
    public static function tableName()
    {
        return '{{%admin_role}}';
    }

    /**
     * 规则
     */
    public function rules()
    {
        return [
            [['rolename','description','listorder'],'required','message'=>'必填'],
            ['rolename','unique','message'=>'角色名重复'],
            [['listorder','status'],'integer','message'=>'排序必须为整数'],
        ];
    }

    /**
     * 属性标签
     */
    public function attributeLabels()
    {
        return [
            'rolename' => '角色名称',
            'description' => '角色描述',
            'listorder'=>'排序',
            'status' => '启用',
        ];
    }

    /**
     * 是否启用
     */
    public function whetherDisabled()
    {
        if($this->status=='0')
        {
            return '启用';
        }
        if($this->status=='2')
        {
            return '禁用';
        }
    }

    /**
     * 关联Role_privs表，关系：一个角色对应一个权限
     */
    public function getRole_privs()
    {
        return $this->hasOne(RolePriv::className(),['roleid' => 'roleid']);
    }

    /**
    * Finds role by roleid 
    * 
    * @param string $roleid 
    * @return array|null 
    */ 
    //查询在role表中是否存在此roleid，若存在就返回一个role的实例
    public function getRolename($roleid)
    {
        $role = Role::find()
        ->where(['roleid' => $roleid])
        ->asArray()
        ->one();
        if($role)
        {
            return $role;
        }
        return null; 
    }
    /**
     * 获取当前角色的权限菜单对象列表
     */
    public function getMenus()
    {
        $roleprivs=RolePriv::find()->where(array('roleid'=>$this->roleid))->asArray()->all();
        $menus=[];
        foreach($roleprivs as $rp)
        {
            $menu=Menu::findOne(array('m'=>$rp['m'],'c'=>$rp['c'],'a'=>$rp['a']));
            $menus[]=$menu;
        }
        return $menus;
    }
    /**
     * 获取当前角色的权限菜单对象列表 
     * 
     * [
     *       'label'=>'管理员设置',
     *       'url'=>'',
     *       'icon'=>'icon-desktop',
     *       'options'=>['class'=>'active'],//
     *       'items'=>[
     *           [
     *               'label'=>'管理员设置',
     *               'icon'=>'icon-double-angle-right',
     *               'url'=>['/admin/admin/index'],
     *           ],
     *           [
     *               'label'=>'角色管理',
     *               'icon'=>'icon-double-angle-right',
     *               'url'=>['/admin/role/index'],
     *           ],
     *           [
     *               'label'=>'站点管理',
     *               'icon'=>'icon-double-angle-right',
     *               'url'=>['/admin/site/index'],
     *           ],
     *       ]
     *   ]
     * 
     * 
     * 
     */
    public function getMenusArray()
    {
        $siteid=Utools::getSiteid();
        $roleprivs=RolePriv::find()->where(array('roleid'=>$this->roleid,'siteid'=>$siteid))->orderBy('id ASC')->asArray()->all();
        $menus=[];
        $curr_module = Yii::$app->controller->module->id;
        $curr_controller = Yii::$app->controller->id;
        $curr_action = Yii::$app->controller->action->id;
        $curr_params = !empty($_SERVER["QUERY_STRING"]) ? '?'.$_SERVER["QUERY_STRING"] : '';
        $curr_url =Yii::$app->request->getUrl();// '/'.$curr_module.'/'.$curr_controller.'/'.$curr_action;//当前地址
        foreach($roleprivs as $rp)
        {
            $where =array('m'=>$rp['m'],'c'=>$rp['c'],'a'=>$rp['a'],'data'=>$rp['data'],'display'=>1,'status'=>0);
            $fields = array('id','cname as label','parentid','icon','listorder','data');
            //查询该权限下有几个按钮
            $menu=Menu::find()->select($fields)->where($where)->asArray()->one();
            if($menu){
                $menu['url']=Url::toRoute(["/$rp[m]/$rp[c]/$rp[a]"]);
                if($menu['data']) $menu['url'] .= '?'.$menu['data'];
                if($menu['url'] == $curr_url){
                    $menu['active'] = true;
                }

                $menus[]=$menu;
                $flag[] = $menu['listorder'];
                $flag_2[] = $menu['id'];
            }else{//有多条按钮,
                unset($menu);
            }
        }

 // print_r($menus);
                  // echo '/backend/web'.$curr_url;

        if($menus)
        {
            array_multisort($flag, SORT_ASC,$flag_2,$menus);//对menus重新排序
//            var_dump($menus);
            $tmenus=$this->treeData($menus);
            //print_r($tmenus);
            return $tmenus;
        }
        else
        {
            return array();
        }
        
    }
    public function treeData($data,$pid = 0,$curr_url=''){
        $result = array();

        foreach($data as $v){
            if($v['parentid'] == $pid){
                $v['items'] = $this->treeData($data,$v['id']);
                $result[] = $v;
            }
        }
        return $result;
    }
    /**
     * 
     * 递归将一维数组转化为多维数组
     * 
     * 
     */
    public function MenuArray($menus)
    {
        foreach($menus as $key=> $menu)
        {
            $tmenus=[];
            foreach($menus as $tkey =>$tmenu)
            {
                
                if(isset($tmenu['parentid'])&&isset($menu['id'])&&$tmenu['parentid']==$menu['id'])
                {
                   
                    $tmenus[]=$tmenu;
                }
            }
            
            if($tmenus)
            {
                $tmenus=$this->MenuArray($tmenus);
                foreach($tmenus as $tmenu)
                {
                    $menus[$key]['items'][]=$tmenu;
                    foreach($menus as $ttkey=>$ttmenu)
                    {
                        //print_r($ttmenu);
                        if($ttmenu['id']==$tmenu['id'])
                        {
                            unset($menus[$ttkey]);
                        }
                    }
                }
            }
           
            
            

        }
        return $menus;
    }
}



?>